<?php

namespace app\merchant\model\store;

use app\common\model\store\User as StoreUserModel;
use org\Redis;
use utils\Random;


/**
 * 商家用户模型
 * Class StoreUser
 * @package app\store\model
 */
class User extends StoreUserModel
{

    private $token;

    const FORM_SCENE_ADD = 'add';
    const FORM_SCENE_EDIT = 'edit';


    /**
     * 商家用户登录
     * @param $data
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login($data)
    {

        $user = self::useGlobalScope(false)->with(['wxapp'])->where(['user_name' =>$data['account'],'is_delete' => 0])->find();

        if(!$user){
            $this->error = '登录失败, 用户名不存在4';
            return false;
        }else{
            $pass= md5(md5($data['password'].$user['salt'].config('salt')));
            if($pass==$user['password']){
                if (empty($user['wxapp'])) {
                    $this->error = '登录失败, 未找到小程序信息';
                    return false;
                }
                if ($user['wxapp']['is_recycle']) {
                    $this->error = '登录失败, 当前小程序商城已删除';
                    return false;
                }
                if($user['wxapp']['active']==0){
                    $this->error = '账号尚未激活，请联系管理员';
                    return false;
                }
                // 保存登录状态
                $this->loginState($user);
                return true;
            }else{
                $this->error = '登录失败, 用户名或密码错误';
                return false;
            }
        }


    }



    /**
     * 获取商户信息
     * @param $token
     * @return null|static
     * @throws \think\exception\DbException
     */
    public function getLoginInfo($token)
    {
        // 记录缓存, 7天
        $redis = new Redis();
        $store_user_id = $redis->hGet('merchant',$token);
        return self::useGlobalScope(false)->where(['store_user_id'=>$store_user_id])->value('user_name');
    }


    /**
     * 获取token
     * @return mixed
     */
    public function getToken()
    {
        return $this->token;
    }


    /**
     * 保存登录状态
     * @param $user
     * @throws \think\Exception
     */
    public function loginState($user)
    {
        // 记录缓存, 2天
        $redis = new Redis();
        // 生成token (session3rd)
        $this->token = $this->token($user['store_user_id']);
        $redis->hSet('merchant',$this->token,$user['store_user_id'],86400 * 2);

    }


    /**
     * 生成用户认证的token
     * @param $openid
     * @return string
     */
    private function token($store_user_id)
    {
        // 生成一个不会重复的随机字符串
        $guid = \getGuidV4();
        // 当前时间戳 (精确到毫秒)
        $timeStamp = microtime(true);
        // 自定义一个盐
        $salt = 'merchant_token_salt';
        return md5("{$timeStamp}_{$store_user_id}_{$guid}_{$salt}");
    }


    /**
     * 获取登录用户信息
     * @param $user_name
     * @param $password
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getLoginUser($store_user_id)
    {
        return  self::useGlobalScope(false)->where(['store_user_id' =>$store_user_id])->find();
    }

    /**
     * 获取管理员列表
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList()
    {
        return $this->where('is_delete', '=', '0')
            ->order(['create_time' => 'desc'])
            ->field('store_user_id,user_name,real_name,is_super,create_time')
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
    }

    /**
     * 新增管理员
     * @param $data
     * @return bool|false|int
     * @throws \think\exception\DbException
     */
    public function add($data)
    {
        // 表单验证
        if (!$this->validateForm($data,self::FORM_SCENE_ADD)) {
            return false;
        }

        $salt= Random::alnum();
        $this->startTrans();
        try {
            $data['salt']  = $salt;
            $data['password'] = md5(md5($data['password'].$salt.config('salt')));
            $data['wxapp_id'] = self::$wxapp_id;
            $data['is_super'] = 0;
            $this->allowField(true)->save($data);
            // 新增角色关系记录
            (new UserRole)->add($this['store_user_id'], $data['role_id']);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }




    /**
     * 编辑管理员
     * @param array $data
     * @return bool
     * @throws \think\exception\DbException
     */
    public function edit($data)
    {   pre($data);
        // 表单验证
        if (!$this->validateForm($data,self::FORM_SCENE_EDIT)) {
            return false;
        }
        if (!empty($data['password'])) {

            $salt = Random::alnum();
            $data['password'] = md5(md5($data['password'].$salt.config('salt')));
            $data['salt'] = $salt;

        } else {
            unset($data['password']);
        }

        $this->startTrans();
        try {
            // 更新管理员记录
            $this->allowField(true)->save($data);
            // 更新角色关系记录
            (new UserRole)->edit($this['store_user_id'], $data['role_id']);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }


    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        if ($this['is_super']) {
            $this->error = '超级管理员不允许删除';
            return false;
        }
        // 删除对应的角色关系
        UserRole::deleteAll(['store_user_id' => $this['store_user_id']]);
        return $this->save(['is_delete' => 1]);
    }

    /**
     * 更新当前管理员信息
     * @param $data
     * @return bool
     */
    public function renew($data)
    {
        if ($data['password'] !== $data['password_confirm']) {
            $this->error = '确认密码不正确';
            return false;
        }
        if ($this['user_name'] !== $data['user_name']
            && self::checkExist($data['user_name'])) {
            $this->error = '用户名已存在';
            return false;
        }
        $salt= Random::alnum();
        // 更新管理员信息
        if ($this->save([
                'user_name' => $data['user_name'],
                // 'password' => yoshop_hash($data['password']),
                'salt'     =>$salt,
                'password' => md5(md5($data['password'].$salt.config('salt')))
            ]) === false) {
            return false;
        }
        // 更新session
        Session::set('yoshop_store.user', [
            'store_user_id' => $this['store_user_id'],
            'user_name' => $data['user_name'],
        ]);
        return true;
    }



    /**
     * 表单验证
     * @param $data
     * @return bool|false|int
     * @throws \think\exception\DbException
     */
    private function validateForm($data,$scene = self::FORM_SCENE_ADD)
    {

        if(!isset($data['user_name']) || empty($data['user_name'])){
            $this->error = '请输入用户名';
            return false;
        }

        if(!isset($data['role_id']) || empty($data['role_id'])){
            $this->error = '请选择角色';
            return false;
        }

        if($scene == self::FORM_SCENE_ADD){

            if(!isset($data['password']) || empty($data['password'])){
                $this->error = '请输入登录密码';
                return false;
            }

            if(!isset($data['password_confirm']) || empty($data['password_confirm'])){
                $this->error = '请输入确认密码';
                return false;
            }

            if (self::detail(['user_name' => $data['user_name'], 'is_delete' => 0])) {
                $this->error = '用户名已存在';
                return false;
            }
        }

        if($scene == self::FORM_SCENE_EDIT){

            if (self::detail(['user_name' => $data['user_name'], 'is_delete' => 0,'store_user_id'=>['neq',$data['store_user_id']]])) {
                $this->error = '用户名已存在';
                return false;
            }
        }


        if ($data['password'] !== $data['password_confirm']) {
            $this->error = '确认密码不正确';
            return false;
        }


        return true;
    }

}
